package com.ipc.app.dal.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.ipc.app.dal.dao.AddressDAO;
import com.ipc.app.dal.doObject.AddressDO;

/**
 * @author haijie.zhang
 * 
 */
public class AddressDAOImpl extends HibernateDaoSupport implements AddressDAO {

	public void batchSave(final List<AddressDO> addressDOs) {
		this.getHibernateTemplate().execute(new HibernateCallback() {

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				for (int i = 0; i < addressDOs.size(); i++) {
					AddressDO addressDO = addressDOs.get(i);
					session.persist(addressDO);
					if (0 == i % 20) {
						session.flush();
						session.clear();
					}
				}
				return null;
			}
		});

	}

	public AddressDO getAddressDO(String addressId) {
		AddressDO addressDO = (AddressDO) this.getHibernateTemplate().get(
				AddressDO.class, addressId);
		return addressDO;
	}

	public void save(AddressDO addressDO) {
		this.getHibernateTemplate().save(addressDO);
	}

	@SuppressWarnings("unchecked")
	public List<AddressDO> getAddressByInformationID(final String informationID) {
		List<AddressDO> addressDOs = (List<AddressDO>) this
				.getHibernateTemplate().execute(new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						Query query = session
								.getNamedQuery("getAddressByInformationID");
						query.setParameter("information_id", informationID);

						List<AddressDO> addressDOs = query.list();
						return addressDOs;
					}
				});
		return addressDOs;
	}
}
